package com.github.gaojh.mvc.filter;

import cn.hutool.core.util.StrUtil;
import com.github.gaojh.ioc.IocUtil;
import com.github.gaojh.ioc.annotation.WebFilter;
import com.github.gaojh.ioc.bean.ClassInfo;
import com.github.gaojh.ioc.bean.ClassScanner;
import com.github.gaojh.ioc.bean.Initializer;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author gaojh
 * @since 2020/3/25
 */
@Slf4j
public class FilterInitializer implements Initializer {
    @Override
    public void init(ClassScanner classScanner) throws Exception {
        List<ClassInfo> list = classScanner.getClassByAnnotation(WebFilter.class);
        for (ClassInfo classInfo : list) {
            WebFilter webFilter = classInfo.getBeanClass().getAnnotation(WebFilter.class);
            if(!Filter.class.isAssignableFrom(classInfo.getBeanClass())){
                log.error("注册过滤器失败：{} 需要实现InterceptorAdapter接口，本次初始化忽略！", classInfo.getBeanName());
                return;
            }
            Filter filter = (Filter) IocUtil.getBean(classInfo.getBeanClass());
            for (String path : webFilter.pathPatterns()) {
                if (StrUtil.isNotBlank(path)) {
                    log.debug("注册过滤器：{} ===> {}", path, classInfo.getBeanName());
                    FilterContext.addInterceptor(webFilter, filter);
                }
            }
        }
    }
}
